. "$PSScriptRoot/common.ps1"

function Rename-ProjectFiles {
    param (
        [string]$rootPath
    )
    # 递归获取所有需要重命名的文件和目录，按路径长度降序排列
    $items = Get-ChildItem -Path $rootPath -Recurse -Force |
             Where-Object { $_.Name -match "JY\.Abp|Jy\.Abp|JY\.Utilities|Jy\.Utilities" } |
             Sort-Object { $_.FullName.Length } -Descending

    foreach ($item in $items) {
        $newName = $item.Name -replace "JY\.Abp", "Jy.Abp" -replace "JY\.Utilities", "Jy.Utilities"
        if ($item.Name -eq $newName) { continue }
        if ($null -eq $item.Directory) { continue }
        $newPath = Join-Path $item.Directory.FullName $newName

        try {
            Rename-Item -Path $item.FullName -NewName $newName -Force
            Write-Host "已重命名: $($item.FullName) => $newPath" -ForegroundColor Green
        }
        catch {
            Write-Host "重命名失败: $($item.FullName) => $newPath" -ForegroundColor Red
            Write-Host "错误信息: $_" -ForegroundColor Red
        }
    }
}

function Update-ProjectReferences {
    param (
        [string]$rootPath
    )
    # 支持的文件类型
    $fileTypes = @("*.csproj","*.sln","*.props","*.targets","*.json","*.md","*.txt","*.cs","*.ps1")
    foreach ($type in $fileTypes) {
        $files = Get-ChildItem -Path $rootPath -Filter $type -Recurse
        foreach ($file in $files) {
            try {
                $content = Get-Content $file.FullName -Raw
                $newContent = $content -replace "JY\.Abp", "Jy.Abp" -replace "JY\.Utilities", "Jy.Utilities"
                if ($content -ne $newContent) {
                    Set-Content -Path $file.FullName -Value $newContent
                    Write-Host "已更新内容: $($file.FullName)" -ForegroundColor Green
                }
            }
            catch {
                Write-Host "更新内容失败: $($file.FullName)" -ForegroundColor Red
                Write-Host "错误信息: $_" -ForegroundColor Red
            }
        }
    }
}

Write-Host "开始重命名项目和目录..." -ForegroundColor Cyan
Rename-ProjectFiles -rootPath $rootFolder

Write-Host "`n开始批量内容替换..." -ForegroundColor Cyan
Update-ProjectReferences -rootPath $rootFolder

Write-Host "`n重命名与内容替换完成！" -ForegroundColor Cyan
Write-Host "请检查以下内容：" -ForegroundColor Yellow
Write-Host "1. 检查所有重命名的文件和目录是否正确" -ForegroundColor Yellow
Write-Host "2. 检查所有类型文件内容是否都已更新" -ForegroundColor Yellow
Write-Host "3. 检查解决方案文件(.sln)中的项目引用" -ForegroundColor Yellow
Write-Host "4. 检查其他可能包含项目名称的文件" -ForegroundColor Yellow 